let timeout: any = null,
	flag: boolean;
/**
 * 防抖原理：一定时间内，只有最后一次操作，再过wait毫秒后才执行函数
 *
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @return null
 */
export function debounce(func: Function, wait = 500) {
	// 清除定时器
	if (timeout !== null) clearTimeout(timeout);
	// 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
	timeout = setTimeout(function () {
		typeof func === 'function' && func();
	}, wait);
}

/**
 * 节流原理：在一定时间内，只能触发一次
 *
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @return null
 */
export function throttle(func: Function, wait = 500) {
	if (!flag) {
		flag = true;
		// 如果是立即执行，则在wait毫秒内开始时执行
		typeof func === 'function' && func();
		setTimeout(() => {
			flag = false;
		}, wait);
	}
}

// 将hex表示方式转换为rgb表示方式(这里返回rgb数组模式)
function hexToRgb(sColor: any, str = true) {
	let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
	sColor = sColor.toLowerCase();
	if (sColor && reg.test(sColor)) {
		if (sColor.length === 4) {
			let sColorNew = '#';
			for (let i = 1; i < 4; i += 1) {
				sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
			}
			sColor = sColorNew;
		}
		//处理六位的颜色值
		let sColorChange = [];
		for (let i = 1; i < 7; i += 2) {
			sColorChange.push(parseInt('0x' + sColor.slice(i, i + 2)));
		}
		if (!str) {
			return sColorChange;
		} else {
			return `rgb(${sColorChange[0]},${sColorChange[1]},${sColorChange[2]})`;
		}
	} else if (/^(rgb|RGB)/.test(sColor)) {
		let arr = sColor.replace(/(?:\(|\)|rgb|RGB)*/g, '').split(',');
		return arr.map((val: any) => Number(val));
	} else {
		return sColor;
	}
}

// 将rgb表示方式转换为hex表示方式
function rgbToHex(rgb: string) {
	let _this = rgb;
	let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
	if (/^(rgb|RGB)/.test(_this)) {
		let aColor = _this.replace(/(?:\(|\)|rgb|RGB)*/g, '').split(',');
		let strHex = '#';
		for (let i = 0; i < aColor.length; i++) {
			let hex = Number(aColor[i]).toString(16);
			hex = String(hex).length == 1 ? 0 + '' + hex : hex; // 保证每个rgb的值为2位
			if (hex === '0') {
				hex += hex;
			}
			strHex += hex;
		}
		if (strHex.length !== 7) {
			strHex = _this;
		}
		return strHex;
	} else if (reg.test(_this)) {
		let aNum = _this.replace(/#/, '').split('');
		if (aNum.length === 6) {
			return _this;
		} else if (aNum.length === 3) {
			let numHex = '#';
			for (let i = 0; i < aNum.length; i += 1) {
				numHex += aNum[i] + aNum[i];
			}
			return numHex;
		}
	} else {
		return _this;
	}
}

/**
 * 求两个颜色之间的渐变值
 * @param {string} startColor 开始的颜色
 * @param {string} endColor 结束的颜色
 * @param {number} step 颜色等分的份额
 * */
export function colorGradient(startColor = 'rgb(0, 0, 0)', endColor = 'rgb(255, 255, 255)', step = 10) {
	let startRGB = hexToRgb(startColor, false); //转换为rgb数组模式
	let startR = startRGB[0];
	let startG = startRGB[1];
	let startB = startRGB[2];

	let endRGB = hexToRgb(endColor, false);
	let endR = endRGB[0];
	let endG = endRGB[1];
	let endB = endRGB[2];

	let sR = (endR - startR) / step; //总差值
	let sG = (endG - startG) / step;
	let sB = (endB - startB) / step;
	let colorArr = [];
	for (let i = 0; i < step; i++) {
		//计算每一步的hex值
		let hex = rgbToHex('rgb(' + Math.round(sR * i + startR) + ',' + Math.round(sG * i + startG) + ',' + Math.round(sB * i + startB) + ')');
		colorArr.push(hex);
	}
	return colorArr;
}

/**
 * 转树形
 * @param items
 * @param idField
 * @param pidField
 * @returns
 */
export function arrayToTree(items: any, idField = 'id', pidField = 'pid') {
	const result: any = []; // 存放结果集
	if (!items) return result;
	const itemMap: any = {}; //
	for (const item of items) {
		const id = item[idField];
		const pid = item[pidField];
		if (!itemMap[id]) {
			itemMap[id] = {
				children: [],
			};
		}
		itemMap[id] = {
			...item,
			children: itemMap[id]['children'],
		};
		const treeItem = itemMap[id];
		if (!pid) {
			result.push(treeItem);
		} else {
			if (!itemMap[pid]) {
				itemMap[pid] = {
					children: [],
				};
			}
			itemMap[pid].children.push(treeItem);
		}
	}
	return result;
}

/**
 * 组装权限数据
 * @param row
 * @param parentId
 * @param permissions
 */
export function recursionPermission(row: any, parentId: number, permissions: any[], prefix = '') {
	let id = permissions.length + 1;
	permissions.push({ id, parentId, name: row.name, permission_id: row.menu_id, permission_type: 1, comment: '菜单类型' });
	// 没有子菜单，渲染权限
	if (!row.children.length) {
		const prefixMiddleStr = row.menu_id.split('.').pop();
		permissions.push({
			id: id + 1,
			parentId: id,
			name: '查看',
			permission_type: 2,
			permission_id: prefix + `/${prefixMiddleStr}/index`,
			tips: '修改格式为:[云函数]/[api路径]',
			comment: '接口类型',
		});
		permissions.push({
			id: id + 2,
			parentId: id,
			name: '添加',
			permission_type: 2,
			permission_id: prefix + `/${prefixMiddleStr}/add`,
			tips: '修改格式为:[云函数]/[api路径]',
			comment: '接口类型',
		});
		permissions.push({
			id: id + 3,
			parentId: id,
			name: '编辑',
			permission_type: 2,
			permission_id: prefix + `/${prefixMiddleStr}/edit`,
			tips: '修改格式为:[云函数]/[api路径]',
			comment: '接口类型',
		});
		permissions.push({
			id: id + 4,
			parentId: id,
			name: '删除',
			permission_type: 2,
			permission_id: prefix + `/${prefixMiddleStr}/del`,
			tips: '修改格式为:[云函数]/[api路径]',
			comment: '接口类型',
		});
		// permissions.push({ id: id + 5, parentId: id, name: '列表', permission_type: 2, permission_id: '', comment: '' });
		// permissions.push({ id: id + 6, parentId: id, name: '批量', permission_type: 2, permission_id: '', comment: '' });
		// permissions.push({ id: id + 7, parentId: id, name: '回收站', permission_type: 2, permission_id: '', comment: '' });
		// permissions.push({ id: id + 8, parentId: id, name: '导入', permission_type: 2, permission_id: '', comment: '' });
		// permissions.push({ id: id + 9, parentId: id, name: '导出', permission_type: 2, permission_id: '', comment: '' });
	} else {
		row.children.map((item: any) => {
			recursionPermission(item, id, permissions, prefix);
		});
	}
}

//向上查找父级菜单
export function findParentItem(pid: any, menuList: any, result: any, idField = 'menu_id', pidField = 'parent_id') {
	let parentMenu = menuList.find((item: any) => item[idField] === pid);
	if (parentMenu) {
		result.unshift(parentMenu);
		if (parentMenu[pidField]) {
			findParentItem(parentMenu[pidField], menuList, result);
		}
	}
}
